<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css"
    />
    <style>
      .container {
        border: 1px solid #000;
      }
      .pageItem {
        display: flex;
      }
    </style>
  </head>
  <body>
    <div class="container mt-2">
      <div class="row">
        <div class="col-lg-12">
          <form>
            <div class="form-group">
              <label for="username">USERNAME</label>
              <input
                id="username"
                class="form-control"
                type="text"
                name="username"
              />
            </div>
            <div class="form-group">
              <label for="sex">SEX</label>
              <input id="sex" class="form-control" type="text" name="sex" />
            </div>
            <div class="form-group">
              <label for="age">AGE</label>
              <input id="age" class="form-control" type="text" name="age" />
            </div>
            <button type="button" id="search" class="btn btn-primary">
              搜索
            </button>
          </form>
        </div>
        <div class="col-12">
          <table
            id="studentTable"
            class="table table-bordered table-striped table-hover mt-2"
            style="text-align: center"
          >
            <thead class="table-info"></thead>
            <tbody></tbody>
          </table>
        </div>

        <div class="col-lg-12">
          <nav aria-label="Page navigation example">
            <ul class="pagination">
              <li class="page-item" onclick="prePage()">
                <a class="page-link" href="#" aria-label="Previous">
                  <span aria-hidden="true">&laquo;</span>
                </a>
              </li>
              <div class="pageItem">
                <li class="page-item active" onclick="choosePage(1,this)">
                  <a class="page-link" href="#">1</a>
                </li>
              </div>
              <li class="page-item" onclick="nextPage()">
                <a class="page-link" href="#" aria-label="Next">
                  <span aria-hidden="true">&raquo;</span>
                </a>
              </li>
            </ul>
          </nav>
        </div>
      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.js"></script>
    <script src="./xhr.js"></script>
    <script>
      var maxPage,
        //当前页先记住,点击1,2,3时给它
        currentPage = 1;
      window.onload = function () {
        // getData();
        //加载有多少个分页,一页显示多少条数据
        getPageTotal();
        choosePage(1);
      };
      function getData() {
        let xhr;
        if (window.XMLHttpRequest) {
          xhr = new XMLHttpRequest();
        } else {
          xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhr.open("get", "/student.do", true);
        xhr.send();

        xhr.onreadystatechange = function () {
          if (xhr.readyState == 4 && xhr.status == 200) {
            let res = JSON.parse(xhr.responseText);
            for (let i = 0; i < res.length; i++) {
              if (res[i]["出生日期"] == null) {
                res[i]["出生日期"] = "未填写";
              } else {
                res[i]["出生日期"] = new Date(
                  res[i]["出生日期"]
                ).toLocaleDateString();
              }
            }
            onloadIndex(res);
          }
        };
      }
      function onloadIndex(data) {
        $("#studentTable thead tr").html("");
        $("#studentTable thead").html("");
        $("#studentTable tbody").html("");
        $("#studentTable thead").html("<tr></tr>");
        for (const item in data[0]) {
          $("#studentTable thead tr").append(`<th>${item}</th>`);
        }
        $("#studentTable thead tr").append(`<th>操作</th>`);
        data.forEach((item, index) => {
          $("#studentTable tbody").append(`
            <tr>
              <td>${item["学号"]}</td>
              <td>${item["姓名"]}</td>
              <td>${item["年龄"]}</td>
              <td>${item["性别"]}</td>
              <td>${item["出生日期"]}</td>
              <td>${item["联系电话"]}</td>
              <td>${item["成绩"]}</td>
              <td>${item["班级"]}</td>
              <td><button onclick=deleteStuPost(${item["学号"]})>删除</button><button>修改</button></td>
            </tr>
          `);
        });
      }
      //以下方法还是get为了测试post 将上面的button onclick事件绑定到post方法中去了
      function deleteStu(stuId) {
        if (window.XMLHttpRequest) {
          xhr = new XMLHttpRequest();
        } else {
          xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhr.open("get", "/delStu.do?stuid=" + stuId, true);
        xhr.send();
        xhr.onreadystatechange = function () {
          let flag;
          if (xhr.status == 200 && xhr.readyState == 4) {
            flag = Boolean(xhr.responseText);
          }
          if (flag) {
            getData();
          }
        };
      }
      //删除方法xhr请求方式post实现

      function deleteStuPost1(stuid) {
        var xhr;
        if (window.XMLHttpRequest) {
          xhr = new XMLHttpRequest();
        } else {
          xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhr.open("post", "/delStu.do");
        //1.在open之后 send之前设置请求头
        xhr //设置请求头(POST)
          .setRequestHeader(
            "Content-Type",
            "application/x-www-form-urlencoded"
          );
        xhr.send(`stuID=${stuid}&name=小明`);
        xhr.onreadystatechange = function () {
          if (xhr.readyState == 4 && xhr.status == 200) {
            let flag = Boolean(xhr.responseText);
            if (flag) {
              getData();
            } else {
              alert("删除失败");
            }
          }
        };
      }

      function deleteStuPost(stuid) {
        xhr({
          url: "/delStu.do",
          type: "json",
          data: { stuid },
          onSuccess(data) {
            getData();
          },
          onFaild(err) {
            console.log(err);
          },
        });
      }
      //请求一共有 多少页的方法
      function getPageTotal() {
        //请求数据库的数据一共有多少条(return total页)
        $.ajax({
          type: "POST", //默认get
          url: "getPage.do", //默认当前页
          success: function (response) {
            let { pageNum } = response[0];
            maxPage = Math.ceil(pageNum / 3);
            for (let i = 2; i <= maxPage; i++) {
              $(".pageItem").append(`
                <li class="page-item" onclick=choosePage(${i},this)><a class="page-link" href="#">${i}</a></li>
              `);
            }
          },
          error: function (e) {
            //请求超时回调
            if (e.statusText == "timeout") {
              alert("请求超时");
            }
          },
          complete: function () {}, //无论请求是成功还是失败都会执行的回调，常用全局成员的释放，或者页面状态的重置
        });
      }
      //点击第几页显示第几页的数据
      function choosePage(num, my) {
        currentPage = num;
        $(my).addClass("active").siblings().removeClass("active");
        $.ajax({
          type: "post",
          url: "getPageData.do",
          data: {
            pageNum: num,
            pageDataSize: 3,
          },
          success: function (data) {
            onloadIndex(JSON.parse(data));
          },
        });
      }
      //点击上一页下一页改变小按钮的class
      function changeIndexClass(index) {
        $($(".pageItem li")[index - 1])
          .addClass("active")
          .siblings()
          .removeClass("active");
      }
      //上一页的方法
      function prePage() {
        if (currentPage > 1) {
          //如果当前页是第二页,我要点击上一页就是2-1
          changeIndexClass(currentPage - 1);
          choosePage(currentPage - 1);
        }
      }
      //下一页
      function nextPage() {
        if (currentPage < maxPage) {
          //如果当前页是第二页,我要点击上一页就是2-1
          changeIndexClass(currentPage + 1);
          choosePage(currentPage + 1);
        }
      }
      $(function () {
        $("button[type='button']").click(function () {
          let name = $("#username").val(),
            sex = $("#sex").val(),
            age = $("#age").val(),
            data = { name, sex, age };
          xhr({
            url: "/searchStu.do",
            type: "json",
            method: "post",
            data,
            onSuccess(res) {
              // getData();
              onloadIndex(JSON.parse(res));
            },
            onFaild(err) {
              console.log(err);
            },
          });
        });
      });
    </script>
  </body>
</html>
